import 'dart:convert';

import 'package:flutter_elf/base/base_page_state.dart';
import 'package:flutter_elf/config/component_index.dart';
import 'package:flutter_elf/model/tv_live_rsp.dart';
import 'package:flutter_elf/page/tv/tv_play_page.dart';
import 'package:flutter_elf/page/video/main.dart';
import 'package:flutter_elf/page/video/window_video_page.dart';
import 'package:flutter_elf/utils/toast_utils.dart';
import 'package:flutter_elf/widgets/custom_underline_tab_indicator.dart';

/// CreateTime 2020/7/2 9:50
/// CreateUser chen 
/// ProjectName flutter_elf
class TvLivePage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return TvLivePageState();
  }
}

class TvLivePageState extends BasePageState<TvLivePage> with TickerProviderStateMixin{
  String url = 'http://chen412115.oss-cn-beijing.aliyuncs.com/tv/tv_live.json';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController = TabController(vsync: this,length: 1);
    f = getData();
  }
  Future<List<TvLiveData>> f;
  List<TvLiveData> channels = [];
  Future<List<TvLiveData>> getData()async{
    TvLiveRsp rsp = await HttpManagers.instance.netFetch<TvLiveRsp>(url, null,method: Method.GET);
    return rsp.data;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<TvLiveData>>(
      future: f,
      builder: (context,snap){
        if(snap.hasData){
          _tabController = TabController(vsync: this,length: snap.data.length);
          return Scaffold(
              appBar: buildAppbar(snap.data),
              body:TabBarView(
                controller: _tabController,
                children: snap.data.map<Widget>((data){
                  return TvLiveItem(data);
                }).toList()
              )
          );
        }else{
          return Material(child: Center(child: Text('loading')),);
        }
      },
    );
//    return Scaffold(
//      body: channels.isEmpty ? Container():ListView(
//        children: channels.map<Widget>((tv){
//          return Column(
//            mainAxisSize: MainAxisSize.min,
//            children: <Widget>[
//              Text(tv.name),
//            ],
//          );
//        }).toList()
//      ),
//    );
  }
  TabController _tabController;
  PreferredSizeWidget buildAppbar(List<TvLiveData> records){
    return PreferredSize(
      preferredSize: Size.fromHeight(130),
      child: Container(
        alignment: Alignment.topCenter,
        padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top,left: 13,right: 13),
        height: 90,
        decoration: BoxDecoration(
          gradient:LinearGradient(colors:  [Color(0xff1c3149),Color(0xff419a91)]),
        ),
        child: Column(
          children: <Widget>[
            TabBar(
              indicator: CustomUnderlineTabIndicator(width: 13,borderSide: BorderSide(width: 1,color: MyColor.appColor),margin: 1),
              unselectedLabelColor: Colors.white,
              labelColor: Colors.white,
              unselectedLabelStyle: TextStyle(fontSize: 15,color: Colors.white),
              labelStyle: TextStyle(fontSize: 18,color: Colors.white),
              indicatorPadding: EdgeInsets.only(bottom: 1),
              indicatorSize: TabBarIndicatorSize.label,
              isScrollable: true,
              indicatorColor: MyColor.appColor,
              indicatorWeight: 2,
              controller: _tabController,
              tabs: records.map((channel){
                return Tab(text:channel.chineseName);
              }).toList(),
            ),
          ],
        ),
      ),
    );
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _tabController.dispose();
  }
}

class TvLiveItem extends StatefulWidget{
  final TvLiveData data;

  TvLiveItem(this.data);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return TvLiveItemState();
  }
}

class TvLiveItemState extends BasePageState<TvLiveItem>{
  @override
  Widget build(BuildContext context) {
    if(widget.data?.channels?.isEmpty ?? true){
      return Center(
        child: Text('没有数据'),
      );
    }
    // TODO: implement build
    return ListView.builder(itemBuilder: (context,index){
      return GestureDetector(
        onTap: (){
          if(widget?.data?.channels[index]?.streams?.firstWhere((s){
            return s.url.endsWith('m3u8');
          },orElse: ()=>null) == null){
            showToast('没有播放源');return;
          }
          String url = widget.data.channels[index].streams.firstWhere((s){
            return s.url.endsWith('m3u8');
          },orElse: ()=>null)?.url ?? '';
          print('播放链接' + url);
          NavigatorUtils.navigatorRouter(context, TvPlayPage(playType: PlayType.network, dataSource: url));
        },
        child: Container(
          height: 50,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text(widget.data.channels[index].name),
            ],
          ),
        ),
      );
    },itemCount: widget.data.channels.length,);
  }
}